package com.poster.entity.vo;


import com.poster.entity.query.SimplePage;
import com.poster.enums.PageSize;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@Data
public class PageVo<T> {

    long pageTotal;
    long countTotal;
    int pageSize;
    int pageNo;
    List<T> data;

    public PageVo(long pageTotal, long countTotal, int pageSize,int pageNo, List<T> data) {
        this.pageTotal = pageTotal;
        this.countTotal = countTotal;
        this.pageSize = pageSize;
        this.pageNo = pageNo;
        this.data = data;
    }

    public static <T> PageVo<T> create(Integer pageNo, Integer pageSize, ISelectPage<T> selectPage){
        long countTotal = selectPage.selectCount();

        if (countTotal <= 0) {
            log.warn("查询的记录返回负数，实现类{}", selectPage.getClass().getName());
            return new PageVo<>(0, 0, 0, 0, null);
        }

        if (pageNo == null || pageNo <= 0){
            pageNo = 1;
        }

        if (pageSize == null || pageSize <= 0){
            pageSize = PageSize.DEFAULT.getSize();
        }

        int pageTotal;
        if (countTotal % pageSize == 0){
            pageTotal = Math.toIntExact(countTotal / pageSize);
        } else {
            pageTotal = Math.toIntExact(countTotal / pageSize + 1);
        }
        int start = (pageNo - 1) * pageSize;
        SimplePage simplePage = new SimplePage();
        simplePage.setStart(start);
        simplePage.setOffset(pageSize);
        List<T> data = selectPage.selectData(simplePage);

        return new PageVo<>(pageTotal, countTotal, pageSize, pageNo, data);
    }
}
